class SessionsController < ApplicationController
  skip_before_action :redirect_if_not_login, only: [:new, :create]
  def new
    if session[:current_user_id].present?
      redirect_to root_path, notice: '已登录！！！'
    end
  end

  def create
    c_user = User.find_by(email: params[:session][:email].to_s.downcase)
    if c_user.present? && c_user.authenticate(params[:session][:password])
      c_user.update_columns(recent_login_ip: request.remote_ip, recent_login_at: Time.now)
      c_user.user_login_logs.create(ip_address: c_user.recent_login_ip, login_at: c_user.recent_login_at)
      session[:current_user_id] = c_user.id
      redirect_to session['return_to_back'] || root_path, notice: '登录成功！！！'
    else
      flash[:notice] = c_user.blank? ? '邮箱名不匹配！！！' : '密码输入错误！！！'
      render 'new'
    end
  end

  def destroy

    session[:current_user_id] = nil
    @current_user = nil
    @current_user_id = nil
    redirect_to root_path, notice: '退出登录成功！！！'
  end
end
